package cn.itsource.hrm.mq.handler;

import cn.itsource.hrm.config.RabbitMQConfig;
import cn.itsource.hrm.vo.PreCreateOrderData;
import com.rabbitmq.client.Channel;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

//预创订单取消Handler
@Component
public class PreCreateOrderCancelHandler {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @RabbitListener(queues = RabbitMQConfig.DELAY_QUEUE_PRE_CREATE_ORDER)
    public void handle(String preCreateOrderSn, Message message, Channel channel){
        //1 获取预创订单 sn--时间到了没有下单（下单了会删除）
        String hashKey = preCreateOrderSn.split("_")[0];
        String hashKkey = preCreateOrderSn.split("_")[1];
        BoundHashOperations<String,String, PreCreateOrderData> operations
                = redisTemplate.boundHashOps(hashKey);
        PreCreateOrderData data = operations.get(hashKkey);
        if (data==null) //已经下单了
            return;

        //2 退库存
        RSemaphore semaphore = redissonClient
                .getSemaphore("kill_course_" + data.getKillCousreId());
        semaphore.release(1);

        //3 删除预创订单
        redisTemplate.opsForHash().delete(hashKey,hashKkey);


        //4 处理完后签收
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
